package controller

import (
	"bytes"
	"context"
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"fmt"
	mssql "github.com/denisenkom/go-mssqldb"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"github.com/tencentyun/cos-go-sdk-v5"
	"io/ioutil"
	"net/http"
	"path/filepath"
	"strconv"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

//func UPloadHandler(c *gin.Context) int {
//	w := c.Writer
//	r := c.Request
//
//	userid := c.PostForm("uid")
//	uid, _ := strconv.Atoi(userid)
//	kindStr := c.PostForm("kind") // 获取表单中的 "kind" 值
//	kind, _ := strconv.Atoi(kindStr)
//	FileType := c.PostForm("FileType")
//	Type, _ := strconv.Atoi(FileType)
//
//	uploadResult, filename := FileUploadHandler(w, r, userid, kind, Type)
//	if uploadResult != "error" {
//		fileID := SendToDatabase(c, uid, kind, uploadResult, filename)
//		return fileID
//	} else {
//		return -1
//	}
//}
//
//func FileUploadHandler(w http.ResponseWriter, r *http.Request, userid string, kind int, Type int) (string, string) {
//
//	if r.Method != "POST" {
//		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
//		return "error", ""
//	}
//
//	// 解析表单数据，包括上传的文件
//	err := r.ParseMultipartForm(10 << 20) // 设置最大文件大小为 10MB
//	if err != nil {
//		http.Error(w, err.Error(), http.StatusInternalServerError)
//		return "error", ""
//	}
//
//	// 获取上传的文件
//	file, _, err := r.FormFile("file")
//
//	//filename := file.Filename
//	if err != nil {
//		http.Error(w, err.Error(), http.StatusBadRequest)
//		return "error", ""
//	}
//	//defer file.Close()
//	FileErr := file.Close()
//	if err != nil {
//		// 处理错误，例如日志记录或返回错误给调用者
//		log.Println("Error closing file:", FileErr)
//		return "error", ""
//	}
//
//	// 根据 "kind" 值设置不同的 uploadDir
//	var uploadDir string //上传目录
//	var Filename string  //文件名
//
//	if Type == 1 {
//		switch kind {
//		case 1:
//			uploadDir = "files/ClubJoinFile"
//			Filename = "《加入社团申请表》.docx"
//		case 2:
//			uploadDir = "files/ClubCreateFile"
//			Filename = "《创建社团申请表》.docx"
//		case 3:
//			uploadDir = "files/ActivityCreateFile"
//			Filename = "《创建活动申请表》.docx"
//		case 4:
//			uploadDir = "files/InspectionFile"
//			Filename = "《年检申请表》.docx"
//		case 5:
//			uploadDir = "files/AwardFile"
//			Filename = "《评优申请表》.docx"
//
//		}
//	}
//	if Type == 2 {
//		switch kind {
//		case 1:
//			uploadDir = "files/ClubJoinFile"
//			Filename = "《加入社团申请表》.pdf"
//		case 2:
//			uploadDir = "files/ClubCreateFile"
//			Filename = "《创建社团申请表》.pdf"
//		case 3:
//			uploadDir = "files/ActivityCreateFile"
//			Filename = "《创建活动申请表》.pdf"
//		case 4:
//			uploadDir = "files/InspectionFile"
//			Filename = "《年检申请表》.pdf"
//		case 5:
//			uploadDir = "files/AwardFile"
//			Filename = "《评优申请表》.pdf"
//
//		}
//	}
//
//	client, err := oss.New("https://oss-cn-beijing.aliyuncs.com", "LTAI5t8CXeoYfcjaXDNGNSjK", "Wg2oijuZdcY7zsY7QoAHlzALtHHFbK")
//	if err != nil {
//		http.Error(w, err.Error(), http.StatusInternalServerError)
//		return "error", ""
//	}
//
//	var objectName string
//	bucketName := "digital-baituan-filestore"
//
//	objectName = generateUniqueFileName(uploadDir, userid, Type)
//
//	bucket, err := client.Bucket(bucketName)
//	if err != nil {
//		http.Error(w, err.Error(), http.StatusInternalServerError)
//		return "error", ""
//	}
//
//	err = bucket.PutObject(objectName, file)
//	if err != nil {
//		http.Error(w, err.Error(), http.StatusInternalServerError)
//		return "error", ""
//	}
//
//	newURL := "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + objectName
//
//	return newURL, Filename
//}

func CreateClub(ctx *gin.Context) {
	uid := ctx.PostForm("uid") //申请创建社团的用户id
	userid, _ := strconv.Atoi(uid)

	ClubName := ctx.PostForm("Cname")

	ClubType := ctx.PostForm("Type")

	Address := ctx.PostForm("Address")
	add, _ := strconv.Atoi(Address)

	CType, _ := strconv.Atoi(ClubType)

	LeaderName := ctx.PostForm("leaderName")

	LeaderID := ctx.PostForm("leaderID")
	Lid, _ := strconv.Atoi(LeaderID)

	college := ctx.PostForm("college")

	createAim := ctx.PostForm("createAim")

	TName := ctx.PostForm("teacherName")

	TeacherID := ctx.PostForm("teacherID")
	Tid, _ := strconv.Atoi(TeacherID)

	TPhone := ctx.PostForm("teacherPhone")

	AdminName := ctx.PostForm("AdminName")

	AdminID := ctx.PostForm("AdminID")
	Adminid, _ := strconv.Atoi(AdminID)

	AdminPhone := ctx.PostForm("AdminPhone")

	ClubMail := ctx.PostForm("clubMail")

	ClubPhone := ctx.PostForm("clubPhone")

	Intro := ctx.PostForm("Introduction")

	Time := ctx.PostForm("CreateTime") //申请创建社团时间

	ApplyCreateTime, _ := time.Parse("2006-01-02 15:04:05", Time) //转换时间的格式
	fmt.Println(ApplyCreateTime)
	var club_state = 0   //社团当前状态默认为全部
	var create_state = 0 //状态是审批中

	var state = 0
	// 得到所连接的数据库
	DB := common.GetDB()

	//判断社长信息是否存在于用户表users中
	var LeaderInfo model.User
	var TeacherInfo model.User
	var AdminInfo model.User

	result1 := DB.Table("users").Where("uid = ? AND uname = ?", Lid, LeaderName).First(&LeaderInfo)
	result2 := DB.Table("users").Where("uid = ? AND uname = ?", Tid, TName).First(&TeacherInfo)
	result3 := DB.Table("users").Where("uid = ? AND uname = ? AND Permission = ?", Adminid, AdminName, 2).First(&AdminInfo) //行政指导老师为超级管理员，需要负责审批工作

	//都能找到信息，能够创建社团
	if result1.RowsAffected > 0 && result2.RowsAffected > 0 && result3.RowsAffected > 0 {

		// 先上传文件
		fileID := UploadFileToCOS(ctx)
		if fileID == -1 {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "文件上传发生错误，请重试")
			return
		}
		state = 1
		club := model.Club{
			Cname:             ClubName,
			Address:           add,
			Type:              CType,
			Aim:               mssql.VarChar(createAim),
			State:             club_state,
			Exist:             create_state,
			Unit:              mssql.VarChar(college),
			TeacherName:       mssql.VarChar(TName),
			TeacherID:         Tid,
			TeacherPhone:      mssql.VarChar(TPhone),
			AdminTeacherName:  mssql.VarChar(AdminName),
			AdminTeacherID:    Adminid,
			AdminTeacherPhone: mssql.VarChar(AdminPhone),
			LeaderID:          Lid,
			LeaderName:        mssql.VarChar(LeaderName),
			Mailbox:           mssql.VarChar(ClubMail),
			Phone:             mssql.VarChar(ClubPhone),
			Introduction:      mssql.VarChar(Intro),
			Edate:             nil, // 设置 Edate 字段为 null
			Odate:             nil, // 设置 Edate 字段为 null
		}

		//插入clubs数据表
		if joinErr := DB.Create(&club).Error; joinErr != nil {
			fmt.Println("执行 SQL 语句时发生错误:", joinErr)
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			return
		}

		// 获得新创建的社团的Cid
		clubID := club.Cid
		fmt.Printf("刚插入的记录的ID: %d\n", clubID)

		clubcreate := model.Apply_CreateClub{
			Cid:       clubID,
			Uid:       userid,
			ApplyTime: ApplyCreateTime,
			State:     create_state,
			File:      fileID,
		}

		//插入申请创建社团分表
		if applyErr := DB.Table("apply_createclub").Create(&clubcreate).Error; applyErr != nil {
			fmt.Println("执行 SQL 语句时发生错误:", applyErr)
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			return
		} else {
			//UploadFileToCOS(ctx)

			applyid := clubcreate.ID
			var kind = 4

			var apply_state = 0

			Title := ClubName + "创建社团申请"

			currentTime := time.Now() //申请时间

			query3 := "INSERT INTO applies (apply_id,uid,kind,approval_state,title,apply_time)VALUES (?,?,?,?,?,?)"

			result := DB.Exec(query3, applyid, uid, kind, apply_state, Title, currentTime)

			if result.Error != nil {
				fmt.Println("执行 SQL 语句时发生错误:", result.Error)
				// response错误提示给前端
				response.Response(ctx, http.StatusBadRequest, 400, nil, "创建社团申请记录插入总表发生错误，请重试")
			}
			//response.Response(ctx, http.StatusOK, 200, nil, "申请创建社团成功")
			response.Success(ctx, gin.H{"state": state}, "申请创建社团成功")

		}

	} else if result1.RowsAffected == 0 {
		//找不到社长信息
		state = 2

		response.Success(ctx, gin.H{"state": state}, "社长信息不存在")
	} else if result2.RowsAffected == 0 {
		//找不到业务指导老师信息
		state = 3
		response.Success(ctx, gin.H{"state": state}, "业务指导老师信息不存在")
	} else if result3.RowsAffected == 0 {
		//找不到业务指导老师信息
		state = 4
		response.Success(ctx, gin.H{"state": state}, "行政指导老师信息不存在")
	} else {
		state = 0
	}
}

//func generateUniqueFileName(dir, uid string, Type int) string {
//	currentTime := time.Now().Format("20060102_150405")
//	var uniqueName string
//	if Type == 1 {
//		uniqueName = dir + uid + "_" + currentTime + ".docx"
//	}
//	if Type == 2 {
//		uniqueName = dir + uid + "_" + currentTime + ".pdf"
//	}
//	return uniqueName
//}

//func SendToDatabase(ctx *gin.Context, uid int, kind int, url string, filename string) int {
//	// 查询数据库
//	DB := common.GetDB()
//
//	FileInfo := model.AllFile{
//		Filename: filename,
//		FileUrl:  url,
//	}
//
//	//插入all file数据表
//	if createErr := DB.Table("all_file").Create(&FileInfo).Error; createErr != nil {
//		response.Response(ctx, http.StatusBadRequest, 400, nil, "插入文件信息发生错误，请重试")
//		return -1
//	} else {
//		Fileid := FileInfo.ID
//		// 返回成功的响应
//		//fmt.Println("文件上传成功！")
//		//response.Success(ctx, gin.H{}, "文件上传数据库成功")
//		//fmt.Println(Fileid)
//		return Fileid
//	}
//}

// UploadToCOS 上传文件到 COS，返回fileID
func UploadFileToCOS(ctx *gin.Context) int {
	file, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "文件上传失败"})
		return -1
	}
	src, err := file.Open()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "无法打开文件"})
		return -1
	}
	defer src.Close()
	content, err := ioutil.ReadAll(src)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "无法读取文件内容"})
		return -1
	}

	// 将文件内容放入bytes.Buffer
	var buf bytes.Buffer
	buf.Write(content)

	uid := ctx.PostForm("uid")
	uidInt, err := strconv.Atoi(uid)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "无法转换uid"})
		return -1
	}
	// 生成唯一的对象键
	objectKey := GenerateUniqueFilename(uidInt) + filepath.Ext(file.Filename)

	// 获取 COS 客户端
	client := common.GetCOS()
	DB := common.GetDB()
	// 设置 COS 上传选项
	opt := &cos.ObjectPutOptions{
		ObjectPutHeaderOptions: &cos.ObjectPutHeaderOptions{
			ContentLength: int64(buf.Len()),
			ContentType:   http.DetectContentType(buf.Bytes()),
		},
	}

	// 上传文件到 COS
	_, err = client.Object.Put(context.Background(), objectKey, &buf, opt)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "上传文件失败: " + err.Error()})
		return -1
	}

	// 构建访问 URL
	url := fmt.Sprintf("https://%s-%s.cos.%s.myqcloud.com/%s", viper.GetString("cos.bucketName"), viper.GetString("cos.appID"), viper.GetString("cos.region"), objectKey)
	newfile := model.AllFile{
		Filename: file.Filename,
		FileUrl:  url,
	}
	if err := DB.Table("all_file").Create(&newfile).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "保存文件失败"})
		return -1
	}

	//ctx.JSON(http.StatusOK, gin.H{"message": "文件上传成功", "fileID": newfile.ID})
	return newfile.ID
}
